/*****************************************************************************
*
*  PROJECT:     SlipStream
*               (CParticle - particles)
*  LICENSE:     GNU General Public License v3 - http://www.gnu.org/licenses/gpl.html

*  DEVELOPERS:  Philip Farquharson	<B00137077@studentmail.uws.ac.uk>
*				John Gray			<B00145524@studentmail.uws.ac.uk>		
*				Zohaib Bhatti		<B00104280@studentmail.uws.ac.uk>
*				Euan Hislop			<B00138636@studentmail.uws.ac.uk>
*
*****************************************************************************/
#include "CParticle.h"

CParticle::CParticle( CVector3 vecPosition, CVector3 vecGravity, CVector3 vecDirection, CVector3 vecDirectionSign, CColor col )
{
	m_vecPosition = vecPosition;
	m_vecDefaultPosition = vecPosition;
	m_vecGravity = vecGravity;
	m_vecDefaultGravity = vecGravity;
	m_vecDirection = vecDirection;
	m_vecDirectionSign = vecDirectionSign;
	m_fLife = 1.0f;
	m_Color = col;
	m_fFade = float(rand()%100)/50.0f+0.009f;
}

void CParticle::Update ( void )
{
	// calculate new position
	float x = m_vecPosition.getX();
	float y = m_vecPosition.getY();
	float z = m_vecPosition.getZ();

	float dxsign = m_vecDirectionSign.getX();
	float dysign = m_vecDirectionSign.getY();
	float dzsign = m_vecDirectionSign.getZ();

	m_fLife = m_fLife - m_fFade;

	if ( m_fLife <= 0 ) // reset
	{
		float dx = dxsign * float((rand()%50)-56.0f)*10.0f * 0.5;
		float dy = dysign * float((rand()%50)-56.0f)*10.0f * 0.5;
		float dz = dzsign * float((rand()%50)-56.0f)*10.0f * 0.5;

		m_vecPosition = m_vecDefaultPosition;
		m_vecGravity = m_vecDefaultGravity;
		m_vecDirection = CVector3(dx, dy, dz);
		m_fLife = 1.0f;
		m_fFade = float(rand()%100)/100.0f+0.003f;
		return;
	}

	if ( y < -39 )
		return;

	float dx = m_vecDirection.getX();
	float dy = m_vecDirection.getY();
	float dz = m_vecDirection.getZ();

	float gx = m_vecGravity.getX();
	float gy = m_vecGravity.getY();
	float gz = m_vecGravity.getZ();

	x += dx / 2000;
	y += dy / 2000;
	z += dz / 2000;

	dx += gx;
	dy += gy;
	dz += gz;

	m_vecPosition.update(CVector3(x, y, z));
	m_vecDirection.update(CVector3(dx, dy, dz));
}

void CParticle::Draw ( void )
{
	glDisable(GL_BLEND);

	float x = m_vecPosition.getX();
	float y = m_vecPosition.getY();
	float z = m_vecPosition.getZ();

	glEnable(GL_TEXTURE_GEN_S);
	glEnable(GL_TEXTURE_GEN_T);
	glEnable( GL_TEXTURE_2D );

	glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
	glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);

	glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

	glPushMatrix();
		glColor4f(m_Color.r, m_Color.g, m_Color.b, m_fLife);
		glTranslatef(x+0.1, y+0.1, z);
		glutSolidSphere(0.04, 4, 4);
	glPopMatrix();

	glDisable(GL_TEXTURE_GEN_S);
	glDisable(GL_TEXTURE_GEN_T);
	glDisable( GL_TEXTURE_2D );

	glEnable(GL_DEPTH_TEST);
}